package com.eiisan.core.mvc.advice;

import com.eiisan.core.exception.ServiceException;
import com.eiisan.core.util.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;

import java.nio.file.AccessDeniedException;

/**
 * @Description: 全局的的异常拦截器
 * @Author: gragonfly
 * @Date: 2019/6/27
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数非法异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result illegalArgumentException(IllegalArgumentException e) {
        log.error("参数非法异常={}", e.getMessage(), e);
        return Result.errorRequest();
    }

    /**
     * 业务异常.
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Result businessException(ServiceException e) {
        log.error("业务异常={}", e.getMessage(), e);
        return Result.errorServe(e.getMessage());
    }

    /**
     * 无权限访问.
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public Result unAuthorizedException(AccessDeniedException e) {
        log.error("业务异常={}", e.getMessage(), e);
        return Result.noAuth();
    }

    /**
     * requestTimesOut异常处理器
     */
    @ExceptionHandler(value = AsyncRequestTimeoutException.class)
    @ResponseStatus(HttpStatus.GATEWAY_TIMEOUT)
    @ResponseBody
    public Result asyncRequestTimeoutExceptionHandler(AsyncRequestTimeoutException e) {
        log.error("业务异常={}", e.getMessage(), e);
        return Result.busyServe();
    }

    /**
     * 全局异常.
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result exception(Exception e) {
        log.info("保存全局异常信息 ex={}", e.getMessage(), e);
        return Result.errorServe();
    }

}
